
package com.example.securityconfig.service.Impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.securityconfig.entity.LoginUser;
import com.example.securityconfig.entity.Result;
import com.example.securityconfig.entity.User;
import com.example.securityconfig.entity.enums.RedisKeyEnum;
import com.example.securityconfig.mapper.UserMapper;
import com.example.securityconfig.service.UserService;
import com.example.securityconfig.util.JsonUtil;
import com.example.securityconfig.util.JwtTokenUtil;
import com.example.securityconfig.util.RedisUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HXB
 * @since 2024-01-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    private final JwtTokenUtil jwtTokenUtil;



    private final RedisUtil redisUtil;

    private final AuthenticationManager authenticationManager;
    public UserServiceImpl(UserMapper userMapper, JwtTokenUtil jwtTokenUtil,  RedisUtil redisUtil, AuthenticationManager authenticationManager) {
        this.userMapper = userMapper;
        this.jwtTokenUtil = jwtTokenUtil;
        this.redisUtil = redisUtil;
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Result<?> loginUser(User loginVo) {
        // 进行用户认证,会调用SecurityLoginService中认证方法
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginVo.getUsername(), loginVo.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        // 认证通过：authenticate!=null  认证不通过：authenticate==null
        if (Objects.isNull(authenticate)){
            throw new UsernameNotFoundException("用户密码错误");
        }
        // 认证通过，开始生成jjwt
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //生成一个不带‘ - ‘的uuid，用来和jwt一起存进redis
        String redisUserKey = UUID.randomUUID().toString().replaceAll("-", "");
        String s = JsonUtil.beanToJson(loginUser);

        //生成随机数  增强安全性
        final String randomKey = jwtTokenUtil.getRandomKey();
        //生成jjwt
        String jwtToken = jwtTokenUtil.generateToken(s, randomKey);
        // 将用户信息存入redis中，uuid作为键
        redisUtil.set(RedisKeyEnum.REDIS_KEY_USER_INFO.getKey()+redisUserKey, jwtToken,RedisKeyEnum.REDIS_KEY_USER_INFO.getExpireTime());
        return Result.success(jwtToken);
    }

    public Result<?> getUserData(Long id) {
        User userData = userMapper.selectById(id);
        userData.setPassword(null);
        return Result.success(userData);
    }

    public Result<?> logout(String token) {
        //根据所传的token删除用户
        redisUtil.del(RedisKeyEnum.REDIS_KEY_USER_INFO.getKey() + token);
        return Result.success("退出成功");
    }

    public Result<?> addUser(User user, Long id) {
        return Result.success();
    }
}
